#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
from scapy.all import *
import random
import sys
import socket
import struct

from scapy.all import IP, TCP, ICMP, IPv6, UDP, Ether, Packet, get_if_hwaddr, get_if_list, sendp

def get_if():
    """获取主机 eth0 接口"""
    iface = None
    for i in get_if_list():
        if "eth0" in i:
            iface = i
            break
    if not iface:
        print("Cannot find eth0 interface")
        exit(1)
    return iface

def send_ipv4(dst_ip, message, iface):
    """发送IPv4数据包"""
    pkt = Ether(src=get_if_hwaddr(iface), dst="ff:ff:ff:ff:ff:ff") / \
          IP(dst=dst_ip) / \
          ICMP() / message
    print(f"Sending IPv4 packet to {dst_ip}:")
    pkt.show2()
    sendp(pkt, iface=iface, verbose=False)

def send_ipv6(dst_ip, message, iface):
    """发送IPv6数据包"""
    pkt = Ether(src=get_if_hwaddr(iface), dst="ff:ff:ff:ff:ff:ff") / \
          IPv6(dst=dst_ip) / \
          UDP(dport=4321, sport=random.randint(49152, 65535)) / message
    print(f"Sending IPv6 packet to {dst_ip}:")
    pkt.show2()
    sendp(pkt, iface=iface, verbose=False)

def writeArp_matchRules(p4info_helper, sw, match_fields_1, match_fields_2, action_params):
    table_entry = p4info_helper.buildTableEntry(
        table_name="MyIngress.arp_match",
    )

def main():
    if len(sys.argv) < 3:
        print("Usage:")
        print("  IPv4: python3 send.py v4 <destination_ip> [message]")
        print("  IPv6: python3 send.py v6 <destination_ipv6> [message]")
        exit(1)

    mode = sys.argv[1]
    dst_ip = sys.argv[2]
    message = sys.argv[3] if len(sys.argv) > 3 else "P4_TEST_PACKET"
    iface = get_if()

    if mode == "v4":
        send_ipv4(dst_ip, message, iface)
    elif mode == "v6":
        send_ipv6(dst_ip, message, iface)
    else:
        print("Invalid mode. Use 'v4' or 'v6'")
        exit(1)

if __name__ == '__main__':
    main()
